package com.caiheng.api.scheduler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.entity.estate.PropertyFeeOrder;
import com.caiheng.api.entity.product.ProductOrder;
import com.caiheng.api.entity.wxuser.UserMp;
import com.caiheng.api.pay.wxpay.WxAppPay;
import com.caiheng.api.service.estate.PropertyFeeOrderService;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.product.ProductOrderService;
import com.caiheng.api.service.wxuser.UserMpService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class DataAnalysis {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private UserMpService userMpService;
    @Resource
    private UserService userService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private PropertyFeeOrderService feeOrderService;

    @Value("${web.wx_notify_url}")
    private String wx_notify_url;//微信支付的回调地址

    @Value("${web.keyPath}")
    private String keyPath;//微信支付的回调地址

    @Value("${web.wx_refund_notify_url}")
    private String wx_refund_notify_url;//微信支付的回调地址

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;
    @Value("${web.mch_id}")
    private String mch_id;
    @Value("${web.api_key}")
    private String api_key;


    @Value("${web.nsh_wyf_notify_url}")
    private String nsh_wyf_notify_url;

    @Value("${web.nsh_notify_url}")
    private String nsh_notify_url;

    @Value("${web.isLocal}")
    private String isLocal;//图片地址


    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    //每5分钟执行一次
    @Scheduled(cron = "0 0/2 * * * ?")
    public void testTasks1() {
        if(isLocal.equals("0")){
            System.out.println("定时任务执行时间：" + simpleDateFormat.format(new Date()));
            String access_token = wxTemplateService.getAccessToken(0);// WxMessage.getACCESSTOKEN(appidMp,secretMp);
            JSONObject jsonObject = WxMessage.getUserMp(access_token,"");
            if(jsonObject != null){
//                System.out.println("同步公众号用户： " + jsonObject.toString());
                if(jsonObject.containsKey("data") && jsonObject.getJSONObject("data").containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                    if(jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String openid = jsonArray.getStr(i);
                            JSONObject userInfo = WxMessage.getUserMpInfo(access_token,openid);
                            if(userInfo!=null && userInfo.size() > 0){
                                String openId = userInfo.getStr("openid");
                                String unionId = userInfo.getStr("unionid");
                                if(StrUtil.isNotEmpty(openId) && StrUtil.isNotEmpty(unionId)){
                                    UserMp userMp = userMpService.selectByUniqueColumn("union_id",unionId);
                                    if(userMp == null){
                                        userMp = new UserMp();
                                        userMp.setOpenId(openId);
                                        userMp.setUnionId(unionId);
                                        userMp.setCreateTime(new Date());
                                        boolean bl = userMpService.save(userMp);
                                    }
                                }
//                            else{
//                                userMp.setLastUpdateTime(new Date());
//                                boolean bl = userMpService.updateById(userMp);
//                            }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     *  每2个小时重置一次数据
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void parameterTasks() {
        parameterService.resetParameter(1);
    }



    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkProductOrderCancel() {
        if(isLocal.equals("0")) {
            try {
                Integer[] states = {0, 1};
                QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
                qw.ne("order_type",6);
                qw.in("status", Arrays.asList(states));
                List<ProductOrder> orderList = productOrderService.list(qw);
                if (CollUtil.isNotEmpty(orderList)) {
                    for (ProductOrder productOrder : orderList) {
                        Date createTime = productOrder.getCreateTime();
                        Date checkTime = DateUtil.getAfterSecondsByOld(createTime, 15 * 60);
                        if (new Date().getTime() > checkTime.getTime()) {
                            //取消订单
                            productOrder.setStatus(5);
                            productOrderService.updateById(productOrder);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    /**
     *  物业费支付中的订单，状态查询处理
     *  每4分钟执行一次
     */
    @Scheduled(cron = "0 0/4 * * * ?")
    public void checkPropertyFeeOrderPaying() {
        if(isLocal.equals("0")) {
            try {
                Integer[] states = {1, 3, 5};
                QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
                qw.in("state", Arrays.asList(states));
                qw.in("pay_platform", 1);
                qw.eq("is_del",0);
                qw.lt("create_time", DateUtil.getAfterSecondsByOld(new Date(),-5 * 60));//5分钟之前的订单
                List<PropertyFeeOrder> orderList = feeOrderService.list(qw);
                if (CollUtil.isNotEmpty(orderList)) {
                    for (PropertyFeeOrder feeOrder : orderList) {
//                        订单状态 0 - 交费申请 1 - 已生成交费清单  2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
                        //已生成交费清单  未提交支付申请的
                        if(feeOrder.getState() == 1){
                            feeOrderService.cancelNoPayOrder(feeOrder);
                        }else{
                            //取消订单
                            feeOrderService.queryOrder(feeOrder);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     *  物业费支付中的订单，状态查询处理
     *  早上4点执行
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void delPropertyFeeOrder() {
        if(isLocal.equals("0")) {
            try {
                //查询1天之前 取消掉的订单
                QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
                qw.eq("state", 5);
                qw.eq("is_del",0);
                qw.le("create_time", DateUtil.getBeforeDayDate(-1) );
                List<PropertyFeeOrder> orderList = feeOrderService.list(qw);
                if (CollUtil.isNotEmpty(orderList)) {
                    for (PropertyFeeOrder feeOrder : orderList) {
                        feeOrder.setIsDel(1);
                        feeOrderService.updateById(feeOrder);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
